/**
 * Created by fengshenhai on 2017/7/25.
 */
(function (w, $, undefined) {
    if (!$) {
        return;
    }

    // replaceParam使用
    // var obj={
    //     hour:12,
    //     minute:30,
    //     second:30
    // }
    //var temp='<em>距开始{dd}</em><span>{hour}</span><font>:</font><span>{minute}</span><font>:</font><span>{second}</span>'
    //Str.replaceParam(temp,obj)
    //输出结果："<em>距开始{dd}</em><span>12</span><font>:</font><span>30</span><font>:</font><span>30</span>"

    //format 使用
    //Str.format('800 {0}px/{1}px "Microsoft YaHei","宋体","Arial Narrow",HELVETICA', '12', '24')
    //依次替换{0}到{n}的值
    var Str = (function () {
        var replaceParam = function (s, data) {
            return s.replace(/{([^{]*?)}/g, function (match, key) {
                return data[key] == null ? match : data[key]
            })
        }//key是捕获到的，match匹配的
        var format = function (s) {
            return replaceParam(s, [].slice.call(arguments, 1))
        }
        return {
            format: format,
            replaceParam: replaceParam
        };
    })();
    //模版引擎
    var tmpl = function (data) {
        var regJs = /<%([\w\W]*?)%>/g,
            regJsExpression = /\bbreak\b|\bcase\b|\bcatch\b|\bcontinue\b|\bdefault\b|\bdelete\b|\bdo\b|\belse\b|\bfinally\b|\bfor\b|\bfunction\b|\bif\b|\breturn\b|\bswitch\b|\bthrow\b|\btry\b|\bvar\b|\bwhile\b|\bwith\b|{|}/g,
            newval = ' var r=[];\n',
            len = 0;
        var append = function (val, script) {
            return script ? (newval += val.match(regJsExpression) ? val + '\n' : 'r.push(' + val + ');\n') : (newval += val != '' ? 'r.push("' + val.replace(/"/g, '\\"') + '");\n' : ''),
                append
        };
        while (match = regJs.exec(data.v)) {
            append(data.v.slice(len, match.index))(match[1], true);
            len = match.index + match[0].length;
        }
        append(data.v.slice(len));
        newval += ' return r.join("");';
        var html = new Function(newval.replace(/[\n\r\t]/g, "")).apply(data.datas);
        if (data.dom) {
            data.dom.html(html);
            data.callback && data.callback();
        } else {
            return html;
        }
    };
    // CSS3({ "transform": "translate3d(100%, 0, 0)" })
    // 输出结果：
    //{
    //-moz-transform:"translate3d(100%, 0, 0)" ,
    //-ms-transform:"translate3d(100%, 0, 0)",
    //-o-transform:"translate3d(100%, 0, 0)",
    //-webkit-transform:"translate3d(100%, 0, 0)",
    //transform:"translate3d(100%, 0, 0)",
    // }
    var CSS3 = function () {
        var o = {}, output;
        var prefix = ["-webkit-", "-moz-", "-ms-", "-o-"];
        if (typeof arguments[0] == "string") {
            o[arguments[0]] = arguments[1];
        } else {
            o = arguments[0];
        }
        for (var k in o) {
            for (var i = 0, len = prefix.length; i < len; i++) {
                o[prefix[i] + k] = o[k];
            }
        }
        return o;
    };
    //countDown({
    //    dom  : that.module.children.countdown.eq(that.scene.length - 1),//jquery dom
    //    date : that.scene[that.scene.length - 1].start,//某个时间节点
    //    temp : '<em>距开始</em><span>{hour}</span><font>:</font><span>{minute}</span><font>:</font><span>{second}</span>',//输出模版
    //    callback: function () {//到达某个时间节点，触发回调
    //          initSecKillData();
    //    }
    //});
    var countDown = function (param) {
        if (!(param.dom && param.dom.length)) {
            return;
        }
        var e = {
            g: param.end ? param.end.getTime() : new Date().getTime(),
            e: param.date.getTime(),
            d: 1000 * 60 * 60 * 24,
            h: 1000 * 60 * 60,
            m: 1000 * 60,
            s: 1000,
            ms: 100
        };
        e.n = e.e - e.g;
        var r = {
            day: '0',
            hour: '0',
            minute: '00',
            second: '00',
            millisecond: '0',
            timeend: true
        };
        if (e.n > 0) {
            r.day = Math.floor(e.n / e.d);
            e.d -= r.day * e.d;
            r.hour = Math.floor(e.n / e.h);
            e.n -= r.hour * e.h;
            r.minute = Math.floor(e.n / e.m);
            e.n -= r.minute * e.m;
            r.second = Math.floor(e.n / e.s);
            e.n -= r.second * e.s;
            r.millisecond = Math.floor(e.n / e.ms);
            for (var a in r) {
                if (a == 'timeend') {
                    continue
                }
                if (r[a] > 0) {
                    r.timeend = false
                }
                if (r[a] < 10 && a != 'millisecond') {
                    r[a] = '0' + r[a]
                } else {
                    r[a] = '' + r[a]
                }
            }
        }
        param.data = r;
        param.dom.html(Str.replaceParam(param.temp, param.data));
        if (Math.floor((e.e - e.g) / 1000 <= 0) && param.callback) {
            param.callback();
            return
        }
        countDown.Timer = setTimeout(function () {
                countDown(param);
            },
            param.time || 1000);
    }

    var ani = function (o) {
        console.log(o);
        console.log(o.$el.html());
        if (!o.$el || !o.$el.length) {
            return;
        }
        var x = o.start, y, step = o.step || 2, ended, duration = o.duration || 1000;
        var ellipse = function (coordinatesX) {
            return 2 * (25 - Math.sqrt(50 * 50 - (coordinatesX - 50) * (coordinatesX - 50)) / 2 );
        }
        var fn = o.fn || ellipse;
        step = o.end > o.start ? step : -1 * step;

        //(duration/timeGap)*2=Math.abs(o.start - o.end)
        //(duration/timGap)=Math.abs(o.start - o.end)/2
        var timeGap = duration / (Math.abs(o.start - o.end) / step);

        var frame = function () {
            x += step;
            ended = (step > 0 && x >= o.end) || (step < 0 && x <= o.end);
            if (ended) {
                x = o.end;
            }
            y = fn(x);
            o.$el.css({
                "left": x + "%",
                "top": y + "%"
            });
            if (ended) {
                o.callback && o.callback();
                return;
            }
            window.requestAnimationFrame ? window.requestAnimationFrame(frame) : setTimeout(frame, timeGap);
        }
        frame();
    };


    var Seckill = function (o) {
        o = o || {};
        this.o = $.extend(
            {
                init: function () {
                },
                before: function () {
                },
                moving: function () {
                },
                after: function () {
                }
            }, o);
        this.init();
    };
    Seckill.prototype = {
        init: function () {
            var that = this;
            that.initData();
            that.initPage();
            that.initCountDown();
            that.bindEvent();
            that.o.init(that);
        },
        initData: function () {
            var that = this;
            that.colorSet = ["#175692", "#f35b6c", "#00245a", "#630358", "#1cb484", "#f7ffe2",
                "#e0ffdc", "#fdfce0", "#fff7f0", "#fcffea", "#ffeeee", "#ffeefd",
                "#ffffd6", "#fff2d6", "#d6f3ff", "#ffe5d6", "#fff9d6", "#ffebde",
                "#e6ffd6", "#e3edff", "#f0e87a", "#cbe99c", "#fbd188", "#ef6848"];
            that.scene = that.o.scene;
            that.loadLock = false;

            that.index = 0;
            var hasIndex = 0;
            var now = new Date();
            $.each(that.scene, function (k, v) {
                v.start = new Date(new Date(v.start).getTime() + 10000);
                v.end = new Date(v.end);
                //now  2017-7-28 09:00
                //活动时间2017-7-27 20:00-22:00  k=0    that.index = 0  hasIndex = 0   v.status=0  本场已经结束
                //活动时间2017-7-28 08:00-09:30  k=1    that.index = 1  hasIndex = 2   v.status=2  距结束
                //活动时间2017-7-28 10:00-12:00  k=2    that.index = 1  hasIndex = 2   v.status=1  距开始
                //活动时间2017-7-28 15:00-17:00  k=3    that.index = 1  hasIndex = 2   v.status=1  距开始

                if (now < v.start) {
                    v.status = 1;
                    if (hasIndex < 1) {
                        that.index = k;
                        hasIndex = 1;
                    }
                } else if (now < v.end) {
                    v.status = 2;
                    if (hasIndex < 2) {
                        that.index = k;
                        hasIndex = 2;
                    }
                } else {
                    v.status = 0;
                }
            });

            that.tmpl = {};
            that.tmpl.countdown = $("#tmpl_countdown").html();
            that.tmpl.ico = $("#tmpl_ico").html();
            that.tmpl.product_list = $("#tmpl_product_list").html();

            that.module = {};
            that.module.ico = $("[data-module=ico]");
            that.module.countdown = $("[data-module=countdown]");
            that.module.product_list = $("[data-module=product_list]");

        },
        initPage: function () {
            var that = this;
            //tmpl({ dom : that.module.ico, v : that.tmpl.ico, datas : that.scene});
            tmpl({dom: that.module.ico, v: that.tmpl.ico, datas: that.scene});
            tmpl({dom: that.module.countdown, v: that.tmpl.countdown, datas: that.scene});
            tmpl({dom: that.module.product_list, v: that.tmpl.product_list, datas: that.scene});


            that.module.children = {};
            that.module.children.ico = that.module.ico.children();
            that.module.children.countdown = that.module.countdown.children();
            that.module.children.product_list = that.module.product_list.children();


            that.module.children.ico.eq(that.index).prev().addClass("ico_left");
            that.module.children.ico.eq(that.index).addClass("ico_center");
            that.module.children.ico.eq(that.index).next().addClass("ico_right");

            that.module.children.countdown.each(function (index) {
                $(this).css(CSS3({"transform": "translate3d(" + 100 * index + "%, 0, 0)"}));
            });
            that.module.children.product_list.each(function (index) {
                $(this).css(CSS3({"transform": "translate3d(" + 100 * index + "%, 0, 0)"}));
            });

            that.renderPage();
        },
        initCountDown: function () {
            var that = this;
            $.each(that.scene, function (k, v) {
                if (v.status == 1) {
                    countDown({
                        dom: that.module.children.countdown.eq(k),
                        date: v.start,
                        temp: '<em>距开始</em><span>{hour}</span><font>:</font><span>{minute}</span><font>:</font><span>{second}</span>',
                        callback: function () {
                            initSecKillData();
                        }
                    });
                } else if (v.status == 2) {
                    countDown({
                        dom: that.module.children.countdown.eq(k),
                        date: v.end,
                        temp: '<em>距结束</em><span>{hour}</span><font>:</font><span>{minute}</span><font>:</font><span>{second}</span>',
                        callback: function () {
                            initSecKillData();
                        }
                    });
                }
            });
        },
        renderPage: function () {
            var that = this;
            //change line color
            var hour = that.module.children.ico.eq(that.index).attr("data-hour");
            var color = hour >= 5 && hour <= 21 ? "#888888" : "#eeeeee";
            $(".time_bar").css({"border-top-color": color});
            //position
            that.module.product_list.css("height", Math.max.apply(null, that.module.children.product_list.map(function () {
                return $(this).height();
            })));
            that.setPos(-100 * that.index + "%", true);
            $("#seckillContent, body, #divBody").css({"background-color": that.colorSet[that.module.children.ico.eq(that.index).attr("data-hour")]});
            //lazyload images when swiping
            $("[tab_lazyload]", that.module.children.product_list.eq(that.index)).each(function () {
                var src = $(this).attr("tab_lazyload");
                $(this).attr("src", src).removeAttr("tab_lazyload");
            });


            var $el = that.module.children.ico.eq(that.index);
            var className = ["ico_ended", "ico_start", "ico_end"];
            $el.find("p").removeClass().addClass(className[that.scene[that.index].status]);
            $el.prev().find("p").removeClass().addClass("ico_ended");
            $el.next().find("p").removeClass().addClass("ico_ended");

            that.index != 0 ? $("#nomore_left").css({ "opacity" : 0 }) : $("#nomore_left").css({ "opacity" : 1 });
            that.index != that.scene.length - 1 ? $("#nomore_right").css({ "opacity" : 0 }) : $("#nomore_right").css({ "opacity" : 1 });

            w.scrollTo(0, 0);
        },
        bindEvent: function () {
            var that = this;
            var pos = {};

            var listOffset = that.module.product_list.offset().top;
            var itemHeight = that.module.children.product_list.eq(0).height() / that.scene[0].product.length;
            var translateY = 0;

            document.addEventListener("touchstart", function (ev) {
                that.o.before(that);
                pos.x1 = ev.touches[0].pageX;
                pos.y1 = ev.touches[0].pageY;
                return;
            }, false);

            document.addEventListener("touchmove", function (ev) {
                pos.x2 = ev.touches[0].pageX;
                pos.y2 = ev.touches[0].pageY;
                var x = pos.x2 - pos.x1;
                var y = pos.y2 - pos.y1;
                if (Math.abs(y) > Math.abs(x)) {
                    that.setPos( - 100 * that.index + "%", true);
                } else {
                    var width = $(window).width();
                    that.setPos(x - that.index * width + "px", false);
                }

                ev.preventDefault();
                return;
            }, false);

            document.addEventListener("touchend", function (ev) {
                pos.x2 = ev.changedTouches[0].pageX;
                pos.y2 = ev.changedTouches[0].pageY;

                var x = pos.x2 - pos.x1;
                var y = pos.y2 - pos.y1;

                console.log(x);

                //区分a链接点击事件
                if (Math.abs(x) < 30 && Math.abs(y) < 30) {
                    return;
                }
                if (Math.abs(y) > Math.abs(x)) {
                    var listHeight = that.module.children.product_list.eq(that.index).height();
                    if (listOffset + listHeight < $(window).height() - itemHeight) {
                        ev.preventDefault();
                        return;
                    }

                    if (y > 0) {
                        translateY -= itemHeight * 2;
                        if (translateY < itemHeight) {
                            translateY = 0;
                        }
                    } else {
                        if (translateY < listOffset) {
                            translateY = listOffset;
                        } else if (translateY + $(window).height() < listOffset + listHeight + itemHeight) {
                            translateY += itemHeight * 2;
                        }
                    }
                    $("#seckillContent").css(CSS3({ "transform" : "translateY(" + -1 * translateY + "px)" }));
                    ev.preventDefault();
                    return;
                }
                var width = $(window).width();
                if (Math.abs(x) < width / 4) {
                    that.setPos( - 100 * that.index + "%", true);
                    ev.preventDefault();
                    return;
                }

                var $el = that.module.children.ico.eq(that.index);
                var $prev = $el.prev();
                var $prev2 = $el.prev().prev();
                var $next = $el.next();
                var $next2 = $el.next().next();


                if (x > 0) {
                    if (that.index == 0) {
                        that.setPos( - 100 * that.index + "%", true);
                        ev.preventDefault();
                        return;
                    }
                    ani({ $el: $prev2, start: 0, end: 10 });
                    $prev2.css({ "opacity" : 1 });
                    ani({ $el: $prev, start: 10, end: 50 });
                    ani({ $el: $el, start: 50, end: 90 });
                    ani({ $el: $next, start: 90, end: 100 });
                    $next.css({ "opacity" : 0 });
                    that.index--;
                } else {
                    if (that.index == that.scene.length - 1) {
                        that.setPos( - 100 * that.index + "%", true);
                        ev.preventDefault();
                        return;
                    }
                    ani({ $el: $prev, start: 10, end: 0 });
                    $prev.css({ "opacity" : 0 });
                    ani({ $el: $el, start: 50, end: 10 });
                    ani({ $el: $next, start: 90, end: 50 });
                    ani({ $el: $next2, start: 100, end: 90 });
                    $next2.css({ "opacity" : 1 });
                    that.index++;
                }
                that.index = that.index <= 0 ? 0 : that.index;
                that.index = that.index == that.scene.length ? that.scene.length - 1 : that.index;

                that.index == that.scene.length - 1 && !that.loadLock && that.loadNextScene();

                translateY = 0;
                $("#seckillContent").css(CSS3({ "transform" : "translateY(0)" }));

                that.renderPage();
                ev.preventDefault();
            });
        },
        setPos: function (pos, needTransition) {
            var that = this;
            var ani = {};
            ani.transition = needTransition ? "all 1s ease" : "none";
            ani.transform = "translate3d(" + pos + ", 0, 0)";
            that.module.product_list.css(CSS3(ani));
            that.module.countdown.show().css(CSS3(ani));
        },
        loadNextScene: function () {

        }
    };

    w.Seckill = Seckill;

})(window, Zepto)

document.addEventListener && document.addEventListener("DOMContentLoaded", function () {
    initSecKillData();
})
function initSecKillData() {
    $.ajax({
        url: './mock_data.txt',
        success: function (datas) {
            if (!datas) {
                return false;
            }
            datas = JSON.parse(datas);
            console.log(datas);
            for (var i = 0; i < datas.length; i++) {
                var tmp = datas[i];
                if (!tmp.product) {
                    tmp.product = new Array();
                }
            }
            new Seckill({"scene": datas});
        }
    });
}